package com.joe.demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-30
 */
public class TestLengthFieldDecoder {

    public static void main(String[] args) {

        final EmbeddedChannel embeddedChannel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024, 0, 4, 1, 5),
                new LoggingHandler(LogLevel.DEBUG)
        );
        
        // 4 个字节的内容长度，实际内容
        final ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        send(buffer, "Hello world");
        send(buffer, "Hi");
        embeddedChannel.writeInbound(buffer);
    }

    private static void send(ByteBuf buffer, String content) {
        // 实际内容
        final byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        // 实际长度
        final int length = bytes.length;
        buffer.writeInt(length);
        buffer.writeByte(1);
        buffer.writeBytes(bytes);
    }
}
